package pilgun.Multithread.Bank;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;

class RandomTransferer implements Runnable{
	private Bank bank;

	private static int MAX_AMOUNT = 40;
	private static int MAX_TRANSFERS = 20;
	public RandomTransferer(Bank bank) {
		this.bank = bank;
	}
	public void run(){

		for(int i = 0;i<MAX_TRANSFERS;i++){
			Account from = bank.getAccount(ThreadLocalRandom.current().nextInt(bank.getAccountNum()));
			Account to = bank.getAccount(ThreadLocalRandom.current().nextInt(bank.getAccountNum()));
			int amount = (int)(ThreadLocalRandom.current().nextInt(MAX_AMOUNT));
			bank.transfer(from, to, amount);
		}
	}
}


public class BankTry {
	private static int ACCOUNT_NUM = 10;
	private static int THREAD_NUM = 20;
	private static int STARTING_BALANCE = 3000;
	private static int MAX_STARTING_INCREASE = 5000; 
	
	
	public static boolean isAllDone(List<Future> results){
		for (Future f: results){
			if (!f.isDone()){
				return false;
			}
		}
		
		return true;
	}
	
	public static void main(String[] args) {
		Bank bank = new Bank();
		
		for (int i=0;i<ACCOUNT_NUM;i++){
			int randAmount = STARTING_BALANCE + (int)(Math.random()*MAX_STARTING_INCREASE);
			bank.addAccount(i, new Account(i, randAmount));
		}
		int before = bank.sum();
		
		ExecutorService pool = Executors.newFixedThreadPool(THREAD_NUM);
		List<Future> results = new ArrayList<Future>();
		for (int i = 0;i<THREAD_NUM;i++){
			 results.add(pool.submit(new RandomTransferer(bank)));
		}		
		pool.shutdown();
		while (!isAllDone(results)){
		}
		int after = bank.sum();
		System.out.println("before: "+before);
		System.out.println("after: "+after);
	}

}
